import { useRouter, useRoute } from 'vue-router';
import { ref, watch } from 'vue';

export { useRouter, useRoute };
export function useNavigate() {
  const router = useRouter();
  const { path: currentPath } = useRoute();

  return function (path, query) {
    if (path === -1) {
      router.back();
    } else {
      if (!path.startsWith('/')) {
        path = `${currentPath}/${path}`;
      }
      router.push({ path, query: { ...query } });
    }
  };
}

export function useLocation() {
  const route = useRoute();

  return {
    hash: route.hash,
    params: route.params,
    path: route.path,
    meta: route.meta,
    name: route.name,
    query: route.query
  };
}

export function useSearchParams() {
  const route = useRoute();
  return route.query;
}

export function useParams() {
  const route = useRoute();
  return route.params;
}

export function useMatches() {
  const route = useRoute();
  const state = ref([]);

  const computedMatches = (values) => {
    state.value = values.map((matched) => ({
      hash: matched.hash,
      path: matched.path,
      name: matched.name,
      meta: matched.meta
    }));
  };
  computedMatches(route.matched);
  watch(() => route.matched, computedMatches);

  return state;
}
